<template>
  <v-row justify="center">
    <v-dialog v-bind="$attrs" v-model="dialog" scrollable :width="width * 1">
      <v-card>
        <v-card-title v-if="title">
          <span>{{ title }}</span>
        </v-card-title>
        <v-divider v-if="title"></v-divider>
        <v-card-text class="px-0 pb-0">
          <v-card flat>
            <slot v-bind:queryParams="queryParams" v-bind:loading="loading" v-bind:search="getList" v-bind:tableData="tableData"/>
            <v-card-actions v-if="total && showPagination">
              <v-spacer></v-spacer>
              <pagination class="pb-0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.limit" @pagination="pagination" />
              <v-spacer></v-spacer>
            </v-card-actions>
          </v-card>
        </v-card-text>
        <v-divider></v-divider>
        <v-card-actions>
          <slot name="footer">
            <v-spacer></v-spacer>
            <v-btn text @click="dialog = false">{{ $t('actions.cancel') }}</v-btn>
            <v-btn color="primary" text @click="$emit('ok')">{{ $t('actions.ok') }}</v-btn>
          </slot>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </v-row>
</template>

<script>
import request from '@/utils/request'
export default {
  props: {
    show: {
      type: Boolean,
      default: false
    },
    api: {
      type: String,
      required: true
    },
    title: String,
    width: {
      type: [Number, String],
      default: 1280
    },
    params: {
      type: Object
    },
    showPagination: {
      type: Boolean,
      default: true
    }
  },
  watch: {
    show(bool) {
      if(bool) {
        this.total = 0
        this.tableData = []
        this.queryParams = {
          page: 1,
          limit: 10
        }
        this.setParams()
        this.getList()
      }
    }
  },
  computed: {
    dialog: {
      get() {
        return this.show
      },
      set(bool) {
        this.$emit('update:show', bool)
      },
      title: String
    }
  },
  data() {
    return {
      loading: false,
      total: 0,
      tableData: [],
      queryParams: {
        page: 1,
        limit: 20
      }
    }
  },
  methods: {
    setParams() {
      if(this.params) {
        for(let key in this.params) {
          this.queryParams[key] = this.params[key]
        }
      }
    },
    pagination() {
      this.getList()
      this.$emit('on-page', this.queryParams.page)
    },
    getList(page) {
      if (/\d+/.test(page)) {
        this.queryParams.page = page
      }
      this.loading = true
      request({
        url: this.api,
        method: 'get',
        params: this.queryParams
      }).then(res => {
        this.total = res.data.count || 0
        this.tableData = res.data.data
      }).finally(() => {
        this.loading = false
      })
    }
  }
}
</script>
